package com.geor.gcv.ict;

import org.opencv.core.Mat;

/**
 * 图像原始和处理矩阵
 */
public class MatMatrix {
	/** 原始矩阵 */
	private Mat src;
	/** 处理后的矩阵 */
	private Mat mat;
	/** 处理数后的数据 */
	private int[] data;

	/** 矩阵默认大小 */
	// private Size size = new Size(30, 30);

	public MatMatrix(Mat mat) {
		super();
		this.src = mat;
		this.data = convert(mat);
	}

	public Mat getSrc() {
		return src;
	}

	/**
	 * 
	 * @param shard
	 *            必须是二值化
	 * @return
	 */
	protected int[] convert(Mat shard) {
		if (shard.rows() > 32 || shard.cols() > 32) {
			throw new RuntimeException("mat format is error!");
		}

		// 缩放到规定大小
		// 将图片信息转换成字节编码
		byte[] bytes = new byte[shard.rows() * shard.cols()];
		int index = 0;
		for (int row = 0; row < shard.rows(); row++) {
			for (int col = 0; col < shard.cols(); col++) {
				if (shard.get(row, col)[0] < 255 / 5 * 2) {
					shard.put(row, col, 0);
					bytes[index++] = 0;
				} else {
					shard.put(row, col, 255);
					bytes[index++] = 1;
				}
			}
		}
		this.mat = shard;
		// 将图片的每一行当做一个int类型处理
		int[] results = new int[shard.rows()];
		index = 0;
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < shard.rows(); i++) {
			for (int j = 0; j < shard.cols(); j++) {
				buffer.append(bytes[index]);
				index++;
			}
			results[i] = Integer.valueOf(buffer.toString(), 2);
			buffer = new StringBuffer();
		}
		return results;
	}

	public Mat getMat() {
		return mat;
	}

	public int[] getData() {
		return data;
	}
}
